//
//  RecommendationSectionController.swift
//  FeastBooking
//
//  Created by Imon on 2017/9/2.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import IGListKit

protocol RecommendationSectionControllerDelegate {
    func showRestaurant(id: Int)
}

final class RecommendationSectionController: ListSectionController {
    
    private var object: [RecommendationResponse]?
    private var itemSize: CGFloat = 0
    var delegate: RecommendationSectionControllerDelegate?
    let loading: UIImage = UIImage(named: "loading_reco")!
    
    override init() {
        super.init()
        let width = UIScreen.main.bounds.width
        itemSize = floor(width / 2.4)
        self.minimumInteritemSpacing = (width - 2 * itemSize) / 3
        self.minimumLineSpacing = self.minimumInteritemSpacing
        inset = UIEdgeInsets(top: 5, left: self.minimumInteritemSpacing, bottom: 5, right: self.minimumInteritemSpacing)
    }
    
    override func numberOfItems() -> Int {
        return object?.count ?? 0
    }
    
    override func sizeForItem(at index: Int) -> CGSize {
        return CGSize(width: itemSize, height: itemSize)
    }
    
    override func cellForItem(at index: Int) -> UICollectionViewCell {
        guard let cell = collectionContext?.dequeueReusableCell(of: RecommendationCell.self, for: self, at: index) as? RecommendationCell else {
            fatalError()
        }
        let reco = object?[index]
        let url = URL(string: (reco?.pictureUrl)!)
        cell.imageView.kf.setImage(with: url, placeholder: loading)
        cell.layoutSubviews()
        return cell
    }
    
    override func didUpdate(to object: Any) {
        self.object = object as? [RecommendationResponse]
    }
    
    override func didSelectItem(at index: Int) {        
        delegate?.showRestaurant(id: object![index].hotelId!)
    }
}
